library(shiny)

# Load precomputed data
sct_data <- readRDS(file = "data/rds/sct_data.rds")
choropleth_data <- readRDS(file = "data/rds/choropleth_data.rds")
parallelcoordinates_data <- readRDS(file = "data/rds/parallelcoordinates_data.rds")
bar_data  <- readRDS(file = "data/rds/bar_data.rds")
radar_data  <- readRDS(file = "data/rds/radar_data.rds")
treemap_data <- readRDS(file = "data/rds/treemap_data.rds")
treemap_data_cities <- readRDS(file = "data/rds/treemap_data_cities.rds")
tree_data <- readRDS(file = "data/rds/tree_data.rds")

server <- function(input, output, session) {

    observe({

        session$sendCustomMessage(type="scatterplot_values", message = sct_data)

    })

    observe({

        session$sendCustomMessage(type="dendrogram_values",
                                  message = list(tree_data,
                                                 bar_data,
                                                 radar_data))

    })

    observe({
        session$sendCustomMessage(type="treemap2_values", message = c(treemap_data,list(treemap_data_cities)))

    })


    observe({

        session$sendCustomMessage(type="choropleth_values", message = choropleth_data)

    })

    observe({

        session$sendCustomMessage(type="parallelcoordinates_values", message = parallelcoordinates_data)

    })

    # Comunication with treemap
    output$text <- renderText({
        req(input$scope)
        req(input$name)

        s <- input$scope
        v <- input$name

        switch(
            s,
            "pais"={
                treemap_data_cities <- subset( treemap_data_cities, pais  == v)
            },
            "regiao"={

                treemap_data_cities <- subset( treemap_data_cities, regiao == v)

            },
            "uf"={
                treemap_data_cities <- subset( treemap_data_cities, uf == v)

            },
            "mesorregiao"={
                treemap_data_cities <- subset( treemap_data_cities, mesorregiao == v)

            },
            "microrregiao"={
                treemap_data_cities <- subset( treemap_data_cities, microrregiao == v)

            },
            "municipio"={
                treemap_data_cities <- subset( treemap_data_cities, municipio == v)

            }
        )

        session$sendCustomMessage(type="treemap2_values_change", message = treemap_data_cities)

        paste("you clicked", input$scope)
    })

}
